<!DOCTYPE html>
<html>
	<head>
		 <meta charset="utf-8">
		<title>练习</title>
		<script src="js/d3.v4.min.js" charset="utf-8"></script>
	</head>
	<body>
		
		<script>
			var dataset=[150,220,360,450,110,130];
			var fruit=["apple","banana","pear","grape","mango","orange"];
			//设置柱形图的参数
			var padding={left:40,top:40,right:40,bottom:40};
			var rectStep=50;
			var rectWidth=40;
			var height=600;
			var width=600;
			//创建画布
			var svg=d3.select("body")
					  .append("svg")
					  .attr("height",height)
					  .attr("width",width);
			//定义比例尺
			var xScale=d3.scaleBand()
						 .domain(fruit)
						 .range([0,rectStep*dataset.length]);
			var max=d3.max(dataset);
			var yScale=d3.scaleLinear()
						 .domain([0,max])
						 .range([0,500])
			
			//添加矩形
			svg.selectAll("rect")					//选择空集
				.data(dataset)						//绑定数据
				.enter()							//获取enter部分
				.append("rect")						//添加矩形
				.attr("x",function(d,i){			//矩形的x位置
					return padding.left+rectStep*i;
				})
				.attr("y",function(d,i){			//矩形的y位置
					return height-padding.bottom-yScale(d);
				})
				.attr("height",function(d){			//矩形的高度
					return yScale(d);
				})
				.attr("width",rectWidth)			//矩形的宽度
				.attr("fill","steelblue")   		//填充颜色
				.on('mouseover',function(){
					d3.select(this)
						.transition()
						.attr('fill','yellow');
//					console.log(d3.select(this).attr('height'));
					console.log(d3.mouse(this));
					console.log(d3.mouse(this)[0]);
				})
				.on('mouseout',function(){
					d3.select(this)
						.transition()
						.attr('fill','steelblue');
				});
			//添加文字
			svg.selectAll("text")
				.data(dataset)
				.enter()
				.append("text")
				.attr("x",function(d,i){
					return padding.left+rectStep*i;
				})
				.attr("y",function(d){
					return height-padding.bottom-yScale(d);
				})
				.attr("dx","8px")
				.attr("dy","1em")
				.text(function(d){
					return d;
				})
				.attr("font-size","14px");

			//添加坐标轴
			var xAxis=d3.axisBottom(xScale);
			svg.append("g")
			   .attr("transform","translate(" + padding.left +"," + (height-padding.bottom)+")")
			   .call(xAxis);
			yScale.range([500,0]);
			var yAxis=d3.axisLeft(yScale);
			svg.append("g")
			   .attr("transform","translate(" + padding.left +","+(height-padding.bottom-500)+")")
			   .call(yAxis);
			   
		</script>
		
	</body>
</html>
